﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectCloth.Entity;
using ProjectCloth.FrmUI.Common;

namespace ProjectCloth.FrmUI
{
    public partial class QuickCheckSaleFrm : UserControl
    {
        private ClothContext db = new ClothContext();
        private List<CashAccount> accounts = new List<CashAccount>();
        public QuickCheckSaleFrm()
        {
            InitializeComponent();
            accounts = db.CashAccounts.ToList();
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;
            var startTime = startDatePiker.Value.Date;
            var txtproductno = txtProductNo.Text;
            var pay = (int)Entity.Enum.OrderStatus.Pay;
            int unpay = (int)Entity.Enum.OrderStatus.Unpay;
            var endTime = endDatePicker.Value.AddDays(1).Date;
            var sql = (from s in db.SaleOrders //.Where(o => (o.OrderStatus == (int)Entity.Enum.OrderStatus.Pay || o.OrderStatus == (int)Entity.Enum.OrderStatus.Unpay))//.ToList()
                       join p in db.SaleOrderItems on s.Id equals p.OrderId
                       join t in db.Products on p.ProductId equals t.Id
                       select new QuickCheck()
                       {
                           OrderId = s.Id,
                           OrderNo = s.OrderNo,
                           Remark = s.Remark,
                           RecordDate = s.RecordDate,
                           InMoneyDate = s.InMoneyDate,
                           OrderItemId = p.Id,
                           ProductNo = t.ProductNo,
                           Amount = s.FinalMoney,
                           InMoneyAccountId = s.InMoneyAccountId,
                           InMoneyAccountName = "",
                           OrderStatus = s.OrderStatus.ToString(),
                       }).Where(o => o.RecordDate >= startTime && o.RecordDate < endTime
                       && ((o.OrderStatus == pay.ToString() || o.OrderStatus == unpay.ToString())
                       && (string.IsNullOrEmpty(txtproductno) || o.ProductNo.Contains(txtproductno))
                       && (string.IsNullOrEmpty(orderNoTxt.Text) || o.OrderNo.Contains(orderNoTxt.Text)))).ToList();
            dataGridView1.DataSource = quickChecksSimple(sql);
        }
        private List<QuickCheck> quickChecksSimple(List<QuickCheck> quicks)
        {
            List<QuickCheck> quickChecks = new List<QuickCheck>();
            foreach (var p in quicks.OrderBy(o => o.OrderItemId))
            {
                if (quickChecks.Where(o => o.OrderId == p.OrderId).Count() <= 0)
                {
                    var quickCheck = p;
                    if (p.InMoneyAccountId > 0)
                        quickCheck.InMoneyAccountName = accounts.Where(o => o.Id == p.InMoneyAccountId).Select(o => o.TradeTypeName).FirstOrDefault();
                    quickCheck.OrderStatus = EnumDefine.GetEnumDescription((Entity.Enum.OrderStatus)(Convert.ToInt32(quickCheck.OrderStatus)));
                    quickChecks.Add(quickCheck);
                }
            }

            return quickChecks;
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
                {
                    #region  开始审核
                    DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
                    if (column is DataGridViewButtonColumn)
                    {
                        var itemId = dataGridView1.CurrentRow.Cells["OrderId"].Value;
                        if (itemId != null && (int)itemId > 0)
                        {
                            var OrderNo = dataGridView1.CurrentRow.Cells["OrderNo"].Value as string;
                            var saleOrder = db.SaleOrders.Where(o => o.OrderNo == OrderNo).FirstOrDefault();
                            var inmoneyId = dataGridView1.CurrentRow.Cells["InMoneyAccountId"].Value != null ? dataGridView1.CurrentRow.Cells["InMoneyAccountId"].Value.ToString() : "0";
                            if (saleOrder == null || ((saleOrder.OrderStatus != (int)Entity.Enum.OrderStatus.Unpay) && (saleOrder.OrderStatus != (int)Entity.Enum.OrderStatus.Pay)))
                            {
                                MessageBox.Show("请确认订单是否存在或则订单状态是否未审核！");
                                return;
                            }
                            if (column.Name == "CheckBtn")
                            {
                                CheckeOrder(OrderNo, Convert.ToInt32(inmoneyId));
                                //var main = MainFrm.CreateInstrance();
                                //var tab = main.Controls.Find("tabControl1", true).FirstOrDefault() as TabControl;
                                //var tabControl = tab;
                                //if (tab != null)
                                //{
                                //    tabControl = tab as TabControl;
                                //}
                                //dataGridView1.CurrentRow.Selected = true;
                                //var instockfrm = new InStockItemFrm((int)itemId);
                                //instockfrm.StartPosition = FormStartPosition.Manual;
                                //instockfrm.Location = new Point(this.Right + 400 - instockfrm.Width, this.Bottom - instockfrm.Height);
                                //instockfrm.ShowDialog(this);//或f.Show(this);或f.Show()
                                searchBtn_Click(null, null);
                            }
                            //else if (column.Name == "OrderNo")
                            //{
                            //    var orderNo = dataGridView1.CurrentRow.Cells["OrderNo"].Value;
                            //    if (orderNo != null)
                            //    {
                            //        var show = new SaleOrderShow(orderNo.ToString());
                            //        show.Show();
                            //    }
                            //}
                        }
                    }
                    else //if(column is DataGridViewColumn)
                    {
                        if (column.Name == "OrderNo")
                        {
                            var orderNo = dataGridView1.CurrentRow.Cells["OrderNo"].Value;
                            if (orderNo != null)
                            {
                                var show =new EditSaleOrderForm(orderNo.ToString());// new SaleOrderShow(orderNo.ToString());
                                show.Location = new Point(this.Location.X + 300, this.Location.Y + 300);
                                show.Show();
                            }
                        }

                    }
                    #endregion

                }
            }
            catch (Exception error)
            {
                MessageBox.Show("出现错误，" + error.Message + ",请稍后再试！");
            }
        }
        private void CheckeOrder(string _orderNo, int inmoneyId)
        {
            var order = db.SaleOrders.AsNoTracking().Where(o => o.OrderNo == _orderNo).FirstOrDefault();
            #region  修改流水记录 变更账户金额
            if (order != null && order.OrderStatus == (int)Entity.Enum.OrderStatus.Pay)
            {
                var cashlog = db.CashAccountLogs.Where(o => o.Source == order.OrderNo && o.VariableAmount > 0).FirstOrDefault();

                var cashAccount = db.CashAccounts.FirstOrDefault(o => o.Id == inmoneyId);
                if (cashAccount != null)
                {
                    order = db.SaleOrders.Where(o => o.OrderNo == _orderNo).FirstOrDefault();
                    order.OrderStatus = (int)Entity.Enum.OrderStatus.Checked;
                    if (cashlog == null || cashlog.VariableAmount <= 0)
                    {
                        var orAmount = cashAccount.Amount;
                        var amount = order.FinalMoney;
                        cashAccount.OriginalAmount = orAmount;
                        cashAccount.Amount += order.OrderNo.EndsWith("T") ? -amount : amount;//区分退货
                        cashAccount.UpdateTime = DateTime.Now;

                        var cashAccountLog = new CashAccountLog();
                        cashAccountLog.CurrentAmount = cashAccount.Amount;
                        cashAccountLog.OriginalAmount = orAmount;
                        cashAccountLog.CashAccountId = cashAccount.Id;
                        cashAccountLog.CreateTime = DateTime.Now;
                        cashAccountLog.LoginId = LoginInfo.GetLoginInfo().UserId;
                        cashAccountLog.MakerId = order.MakerId;
                        cashAccountLog.MakerTime = order.RecordDate;
                        cashAccountLog.RelatedObject = order.CustomerName;
                        cashAccountLog.Source = order.OrderNo;
                        cashAccountLog.Remark = order.Remark + (order.OrderNo.EndsWith("T") ? "退货单" : "");
                        cashAccountLog.VariableAmount = order.OrderNo.EndsWith("T") ? -order.FinalMoney : order.FinalMoney;
                        cashAccountLog.CashAccountId = (int)inmoneyId;//建议直接读取id
                        db.CashAccountLogs.Add(cashAccountLog);
                    }
                    var result = db.SaveChanges();
                    if (result > 0)
                    {
                        MessageBox.Show("审核成功！");
                    }
                }
                else { MessageBox.Show("收款账号不存在！"); }

            }
            else
            {
                MessageBox.Show("请确定该销售单是否存在或者状态是否为已支付！");
            }
            #endregion
        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dataGridView1.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
    }

    internal class QuickCheck
    {
        public int OrderId { get; set; }
        public string OrderNo { get; set; }
        public string Remark { get; set; }
        public DateTime RecordDate { get; set; }
        public DateTime InMoneyDate { get; set; }
        public int OrderItemId { get; set; }
        public string ProductNo { get; set; }
        public decimal Amount { get; set; }
        public int? InMoneyAccountId { get; set; }
        public string InMoneyAccountName { get; set; }
        public string OrderStatus { get; set; }

        //public QuickCheck(int orderId, string orderNo, string remark, DateTime recordDate, DateTime inMoneyDate, int orderItemId, string productNo, decimal amount, int? inMoneyAccountId, string inMoneyAccountName, int orderStatus)
        //{
        //    OrderId = orderId;
        //    OrderNo = orderNo;
        //    Remark = remark;
        //    RecordDate = recordDate;
        //    InMoneyDate = inMoneyDate;
        //    OrderItemId = orderItemId;
        //    ProductNo = productNo;
        //    Amount = amount;
        //    InMoneyAccountId = inMoneyAccountId;
        //    InMoneyAccountName = inMoneyAccountName;
        //    OrderStatus = orderStatus;
        //}

        public override bool Equals(object obj)
        {
            return obj is QuickCheck other &&
                   OrderId == other.OrderId &&
                   OrderNo == other.OrderNo &&
                   Remark == other.Remark &&
                   RecordDate == other.RecordDate &&
                   InMoneyDate == other.InMoneyDate &&
                   OrderItemId == other.OrderItemId &&
                   ProductNo == other.ProductNo &&
                   Amount == other.Amount &&
                   InMoneyAccountId == other.InMoneyAccountId &&
                   InMoneyAccountName == other.InMoneyAccountName &&
                   OrderStatus == other.OrderStatus;
        }

        public override int GetHashCode()
        {
            var hashCode = -1411124279;
            hashCode = hashCode * -1521134295 + OrderId.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(OrderNo);
            hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Remark);
            hashCode = hashCode * -1521134295 + RecordDate.GetHashCode();
            hashCode = hashCode * -1521134295 + InMoneyDate.GetHashCode();
            hashCode = hashCode * -1521134295 + OrderItemId.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(ProductNo);
            hashCode = hashCode * -1521134295 + Amount.GetHashCode();
            hashCode = hashCode * -1521134295 + InMoneyAccountId.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(InMoneyAccountName);
            hashCode = hashCode * -1521134295 + OrderStatus.GetHashCode();
            return hashCode;
        }
    }
}
